package edu.hawaii.duedates;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Due Dates main class for logging in to various libraries and 
 * retrieving due date information. The class uses the LibraryVault 
 * object and HttpUnit classes to login and scan a given web page for due 
 * date information. 
 * 
 * @author Tyler Wolff and Scheller Sanchez
 */
public class DueDatesGold {
  
  /**
   * Attempts to login to a given Library system with user information. 
   * System makes use of an HttpUnit WebConversation to scan a systems 
   * web page for login form, then inputs user information and submits. 
   *   
   * @param libSystem The library system to login to.
   * @param id The user ID or first login parameter. 
   * @param pass The user password or second login parameter. 
   * @return The WebConversation instance after successful login. 
   * @throws Exception If login was not successful with these credentials. 
   */
  protected WebConversation login(LibraryVault libSystem, String id, String pass) throws Exception {

      // If website has bogus JavaScript code, do not throw error.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(libSystem.libUrl);
      WebResponse response = conversation.getResponse(request);
      WebForm form = response.getFormWithName(libSystem.formName);
      form.setParameter(libSystem.param1, id);
      form.setParameter(libSystem.param2, pass);
      form.submit();
      response = conversation.getCurrentPage();
      
        if (response.getText().contains("Sorry, Login unsuccessful")) {
          conversation = null;
          System.out.println("Login was unsuccessful. Please try again.");
        }
        
      return conversation;
      
  }
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   *  
   * @param libSystem The systems libraryVault object.
   * @param id The UH user ID. 
   * @param lastName  The UH user's last name.    
   * @return A String containing information about their books.
   * @throws LoginException If problems occur parsing the site pages. 
   */
  public String[] getUhInfo(LibraryVault libSystem, String id, 
                            String lastName) throws LoginException {
    
    String uhSiteNoItemString = "You have no items checked out.";
    
    try {
      WebConversation conversation = this.login(libSystem, id, lastName);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      if (uhSiteNoItemString.equals(form.getText())) {
        return null;
      }
      else {
        // Assume the first table is the one we need. Not true in general.
        WebTable table = response.getTableStartingWith( "Renew?" );
        String [] bookInfo = new String[((table.getRowCount() - 1) * 3)];
        int arrayInc = 0;
        
        for (int i = 1; i < table.getRowCount(); i++) {
          bookInfo[arrayInc]  = table.getCellAsText(i, 1);
          bookInfo[arrayInc + 1] = table.getCellAsText(i, 2);
          bookInfo[arrayInc + 2] = table.getCellAsText(i, 3);
          arrayInc = arrayInc + 3;
        }
        return bookInfo;
      } //end else
    } //end try
    catch (Exception e) {
      throw new LoginException(e);
    }
  }

  /**
   * Utilizes a users information to login to a given library system
   * and gather data about the users current check out books. 
   * 
   * @param params two strings: uhID, uhLastName.
   * @throws Exception If problems occur accessing the library sites. 
   */
  public static void main(String[] params) throws Exception {
    
    String uhUrl = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    String format = "|%1$-50s|%2$-20s|%3$-25s|\n";            //format for output table
    
    //creating libraryVault object for UH Manoa Library
    LibraryVault uhManoa;
    uhManoa = new LibraryVault(uhUrl,"logonpage", "BC", "LN");
    DueDatesGold dueDate = new DueDatesGold();
    
    // Check UH Manoa Library
    String uhId = params[0];
    String uhLastName = params[1];
    System.out.printf("Loging into UH Manoa Library%n");
    String[] uhInfo = dueDate.getUhInfo(uhManoa, uhId, uhLastName);
    System.out.printf("Results for UH Manoa Library:%n");
    
    if (uhInfo == null) {
      System.out.println("You have no items currently checked out.");
    } 
    else {
      System.out.format(format, "ITEM DESCRIPTION", "ITEM TYPE", "DUE DATE");
      for (int i = 0; i < uhInfo.length; i = i + 3) {
        System.out.format(format, uhInfo[i].substring(0, 47) + "...", uhInfo[i + 1], uhInfo[i + 2]);
      }
    }
    
  }
}
